package com.njitweb.service.impl;

import com.njitweb.mapper.UserMapper;
import com.njitweb.pojo.User;
import com.njitweb.exception.LoginException;
import com.njitweb.service.UserService;
import com.njitweb.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userDao;

    @Override
    public Map<String, Object> login(User user) {
        if (StringUtils.isEmpty(user.getUsername())||user.getUsername()=="") {
            throw new LoginException("用户名");
        }

        User selctedUser = userDao.selectByUser(user.getUsername());
        if (selctedUser == null) {
            throw new LoginException("用户不存在,请重新输入");
        }
        //密码进行加密  MD5 加密
        String password = user.getPassword();

        if (!password.equals((selctedUser.getPassword()))) {
            throw new LoginException("密码错误,请重新登录");
        }

        // 生成JWT的临牌
        Map<String, Object> map = new HashMap<>();
        Integer id = selctedUser.getId();
        map.put("username", selctedUser.getUsername());
        map.put("id", id);
        String token = JWTUtil.createJWT("njitzx", 1000 * 3600 * 10, map);
        map.put("token", token);
        //生存JWT token 校验
        return map;
    }
}
